<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件

//设置错误级别（例：修正输出数组中未有的变量时报错）
error_reporting(E_ERROR | E_PARSE);

//验证某方法是否有权限
function checkPermission($rule){
    if(empty($rule)) return true;
    $menus = session(request()->module() . '_menus');
    if(empty($menus)){
        return false;
    }
    $menuData = db('admin_menu')->where(array('module' => request()->module(),'path' => $rule))->find();
    if($menuData){ //有此权限配置时判断
        if(!in_array($menuData['id'],$menus)){
            return false;
        }
    }
    return true;
}

//转化为xml
function toXml($arr){
    $xml = "<xml>";
    foreach ($arr as $key=>$val)
    {
        if (is_numeric($val)){
            $xml.="<".$key.">".$val."</".$key.">";
        }else{
            $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
        }
    }
    $xml.="</xml>";
    return $xml;
}

//获取tree模式
function genTree($items,$id='id',$pid='pid',$son = 'children'){
    $tree = array(); //格式化的树
    $tmpMap = array(); //临时扁平数据
    foreach ($items as $item) {
        $tmpMap[$item[$id]] = $item;
    }
    foreach ($items as $item) {
        if (isset($tmpMap[$item[$pid]])) {
            $tmpMap[$item[$pid]][$son][] = &$tmpMap[$item[$id]];
        } else {
            $tree[] = &$tmpMap[$item[$id]];
        }
    }
    unset($tmpMap);
    return $tree;
}
/**
 * 检查是否微信终端
 */
function checkIfWeiXinClientType()
{
    $clientAgent = strtolower($_SERVER['HTTP_USER_AGENT']);
    return strpos($clientAgent, "micromessenger");
}

/**
 * 将从数据库中读取的文案数据转化成前端显示数据
 *
 * @param $dbSrc
 *
 * @return string
 */
function convert_doc_content($dbSrc)
{
    return htmlspecialchars_decode(html_entity_decode($dbSrc));
}

/**
 * 格式验证
 * @param $value
 * @param $rule
 * @return bool
 */
function regex($value, $rule)
{
    $validate = array(
        'username' => '/^\w{3,20}$/',
        'password' => '/^[A-Za-z0-9_]{6,20}$/',
        'nickname' => '/^\w{1,6}$/',
        'phone' => '/^1[134578]{1}[0-9]{9}$/',
        'require' => '/\S+/',
        'email' => '/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/',
        'url' => '/^http(s?):\/\/(?:[A-Za-z0-9-_]+\.)+[A-Za-z]{2,4}(?:[\/\?#][\/=\?%\-&~`@[\]\':+!\.#\w]*)?$/',
        'currency' => '/^\d+(\.\d+)?$/',
        'number' => '/^\d+$/',
        'zip' => '/^\d{6}$/',
        'integer' => '/^[-\+]?\d+$/',
        'double' => '/^[-\+]?\d+(\.\d+)?$/',
        'english' => '/^[A-Za-z]+$/',
        'money' => "/^([1-9][\d]{0,7}|0)(\.[\d]{1,2})?$/",
    );
    // 检查是否有内置的正则表达式
    if (isset($validate[strtolower($rule)]))
        $rule = $validate[strtolower($rule)];

    return preg_match($rule, $value) === 1;
}

function encryptUserPwd($password)
{
    return base64_encode(hash('sha256', $password, false));
}


/**
 * 系统加密方法
 *
 * @param string $data
 *            要加密的字符串
 * @param string $key
 *            加密密钥
 * @param int $expire
 *            过期时间 (单位:秒)
 *
 * @return string
 */
function ucenter_encrypt($data, $key = 'asdfasd#sdfjJJ134@sdjf^%', $expire = 0)
{
    $key = md5($key);
    $data = base64_encode($data);
    $x = 0;
    $len = strlen($data);
    $l = strlen($key);
    $char = '';
    for ($i = 0; $i < $len; $i++) {
        if ($x == $l) {
            $x = 0;
        }
        $char .= substr($key, $x, 1);
        $x++;
    }
    $str = sprintf('%010d', $expire ? $expire + time() : 0);
    for ($i = 0; $i < $len; $i++) {
        $str .= chr(ord(substr($data, $i, 1)) + (ord(substr($char, $i, 1))) % 256);
    }

    return str_replace('=', '', base64_encode($str));
}

/**
 * 系统解密方法
 *
 * @param string $data
 *            要解密的字符串 （必须是ucenter_encrypt方法加密的字符串）
 * @param string $key
 *            加密密钥
 *
 * @return string
 */
function ucenter_decrypt($data, $key = 'asdfasd#sdfjJJ134@sdjf^%')
{
    $key = md5($key);
    $x = 0;
    $data = base64_decode($data);
    $expire = substr($data, 0, 10);
    $data = substr($data, 10);
    if ($expire > 0 && $expire < time()) {
        return '';
    }
    $len = strlen($data);
    $l = strlen($key);
    $char = $str = '';
    for ($i = 0; $i < $len; $i++) {
        if ($x == $l) {
            $x = 0;
        }
        $char .= substr($key, $x, 1);
        $x++;
    }
    for ($i = 0; $i < $len; $i++) {
        if (ord(substr($data, $i, 1)) < ord(substr($char, $i, 1))) {
            $str .= chr((ord(substr($data, $i, 1)) + 256) - ord(substr($char, $i, 1)));
        } else {
            $str .= chr(ord(substr($data, $i, 1)) - ord(substr($char, $i, 1)));
        }
    }

    return base64_decode($str);
}

function https_request($url)
{
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_TIMEOUT, 500);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($curl, CURLOPT_URL, $url);
    $res = curl_exec($curl);
    curl_close($curl);
    return $res;
}


/**
 * 验证身份证号是否正确
 * @param $id
 * @return bool
 */
function check_idcard($id)
{
    $id = strtoupper($id);
    $regx = "/(^\d{15}$)|(^\d{17}([0-9]|X)$)/";
    $arr_split = array();
    if (!preg_match($regx, $id)) {
        return FALSE;
    }
    if (15 == strlen($id)) //检查15位
    {
        $regx = "/^(\d{6})+(\d{2})+(\d{2})+(\d{2})+(\d{3})$/";

        @preg_match($regx, $id, $arr_split);
        //检查生日日期是否正确
        $dtm_birth = "19" . $arr_split[2] . '/' . $arr_split[3] . '/' . $arr_split[4];
        if (!strtotime($dtm_birth)) {
            return FALSE;
        } else {
            return TRUE;
        }
    } else      //检查18位
    {
        $regx = "/^(\d{6})+(\d{4})+(\d{2})+(\d{2})+(\d{3})([0-9]|X)$/";
        @preg_match($regx, $id, $arr_split);
        $dtm_birth = $arr_split[2] . '/' . $arr_split[3] . '/' . $arr_split[4];
        if (!strtotime($dtm_birth)) //检查生日日期是否正确
        {
            return FALSE;
        } else {
            //检验18位身份证的校验码是否正确。
            //校验位按照ISO 7064:1983.MOD 11-2的规定生成，X可以认为是数字10。
            $arr_int = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
            $arr_ch = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
            $sign = 0;
            for ($i = 0; $i < 17; $i++) {
                $b = (int)$id{$i};
                $w = $arr_int[$i];
                $sign += $b * $w;
            }
            $n = $sign % 11;
            $val_num = $arr_ch[$n];
            if ($val_num != substr($id, 17, 1)) {
                return FALSE;
            } //phpfensi.com
            else {
                return TRUE;
            }
        }
    }

}

/**
 * 获取两个坐标之间的距离
 * @param $lat1
 * @param $lng1
 * @param $lat2
 * @param $lng2
 * @param int $len_type 1-米;2-千米
 * @return float
 */
function getCoordinateDistance($lng1, $lat1, $lng2, $lat2, $len_type = 2)
{
    $pi = 3.1415926;
    $earth_radius = 6378.137; //地球半径
    $radLat1 = $lat1 * $pi / 180.0;
    $radLat2 = $lat2 * $pi / 180.0;
    $a = $radLat1 - $radLat2;
    $b = ($lng1 * $pi / 180.0) - ($lng2 * $pi / 180.0);
    $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2)));
    $s = $s * $earth_radius;
    $s = round($s * 1000);
    if ($len_type > 1) {
        $s = $s / 1000;
    }
    return round($s, 1);
}

/**
 * 生成商品唯一编码
 * @return string
 */
function create_goods_sn() {
    $goods_sn = mb_substr(date('Ymd'), 2, 8, 'utf-8') . substr(time() . '', -4);
    $info = db('goods')->where(array('goods_sn' => $goods_sn))->find();
    return $info ? create_goods_sn() : $goods_sn;
}

/**
 * 生成唯一用户邀请码
 * @return bool|mixed|string
 */
function create_user_invite_code() {
    $randStr = str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZ');
    $randId = substr($randStr, 0, 8);
    $info = db('user')->where(array('invite_code' => $randId))->find();
    return $info ? create_user_invite_code() : $randId;
}

//生成唯一订单号,支付单号
function create_order_sn($table = '', $column = 'order_sn', $orderPrefix = 'G') {
    $order_code = $orderPrefix .
        mb_substr(date('Ymd'), 0, 8, 'utf-8') .
        sprintf("%04s", rand(0, intval(substr(time() . '', -4))));
    $info = db($table)->where(array($column => $order_code))->find();
    return $info ? create_order_sn($table, $column, $orderPrefix) : $order_code;
}

/**
 * PHP格式化字节大小
 * @param  number $size      字节数
 * @param  string $delimiter 数字和单位分隔符
 * @return string            格式化后的带单位的大小
 */
function format_bytes($size, $delimiter = '') {
    $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
    for ($i = 0; $size >= 1024 && $i < 5; $i++) $size /= 1024;
    return round($size, 2) . $delimiter . $units[$i];
}

function get_file_list(){
    $file_list = [];
    $file_path = resource_path('views\home');
    if (is_dir($file_path)){
        $handler = opendir($file_path);
        while( ($filename = readdir($handler)) !== false ) {
            if($filename != "." && $filename != ".."){
                $file_list[] = $filename;
            }
        }
        closedir($handler);
        return $file_list;
    }
}

/**
 * 获取目录里的文件，不包括下级文件夹
 * @param string $dir  路径
 * @return array
 */
function get_dir($dir){
    $file = @ scandir($dir);
    foreach($file as $key){
        if ( $key != ".." && $key != "." ){
            $files[] = $key;
        }
    }
    return $files;
}
//获取文件夹中的文件,含目录
function dir_list($path, $exts = '', $list= array()) {
    $path = dir_path($path);
    $files = glob($path.'*');
    foreach($files as $v) {
        $fileext = fileext($v);
        if (!$exts || preg_match("/\.($exts)/i", $v)) {
            $list[] = $v;
            if (is_dir($v)) {
                $list = dir_list($v, $exts, $list);
            }
        }
    }
    return $list;
}
/**
 * 补齐目录后的/
 * @param $path 目录
 * @return string
 */
function dir_path($path) {
    $path = str_replace('\\', '/', $path);
    if(substr($path, -1) != '/') $path = $path.'/';
    return $path;
}
/**
 * 查找文件后缀
 * @param $filename 文件名称
 * @return string 后缀名称（如：html）
 */
function fileext($filename) {
    return strtolower(trim(substr(strrchr($filename, '.'), 1, 10)));
}
//删除目录及文件
function dir_delete($dir) {
    $dir = dir_path($dir);
    if (!is_dir($dir)) return FALSE;
    $list = glob($dir.'*');
    foreach($list as $v) {
        is_dir($v) ? dir_delete($v) : @unlink($v);
    }
    return @rmdir($dir);
}